var initParams = {
		voltage:$('#voltage').val(),
		second:$('#second').val(),
		start:$('#startParam').val(),
		end:$('#endParam').val()
};
var queryMonitorResultDiv = $('#queryMonitorResultDiv');
var queryMonitorResultLoadingDiv = $('#queryMonitorResultLoadingDiv');
var queryLineResultDiv = $('#queryLineResultDiv');
var queryLineResultLoadingDiv = $('#queryLineResultLoadingDiv');
var queryMonitorResultNoDataDiv = $('#queryMonitorResultNoDataDiv');
var detailDiv = $('#detailDiv');

var lineMonitors = new LineMonitors();
var iceMonitorChart = new IceMonitorChart();
var iceMonitorTable = new IceMonitorTable();

var currentLineName;
var currentMonitorId;
var startDate;
var endDate;
var queryIndex = 0;

initData();
function initData() {
	if(initParams.second){
		var timemult = new Date().getTime();
		var start = new Date( timemult - initParams.second*1000);
		var end = new Date();
		startDate = getDate(start);
		endDate = getDate(end);
	}else{
		startDate = initParams.start;
		endDate = initParams.end;
	}
	$('#start').val(startDate);
	$('#end').val(endDate);
	$('#start').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	$('#end').datetimepicker({
		format : 'yyyy-mm-dd',
		minView : 2,
		autoclose : true,
		endDate : new Date(),
		todayHighlight : true
	});
	var url = "/rest/ice/getLineMonitorListDialogInitData/" + initParams.voltage;
	if(initParams.second){
		url += "/"+initParams.second;
	}else{
		url += "/"+startDate+"/"+endDate;
	}
	$.getJSON(url, function(result) {
		queryLineResultDiv.show();
		queryLineResultLoadingDiv.hide();
		data = result;
		drawLineNames(data.ice);
		currentLineName = data.ice[0];
		currentMonitorId = data.defaultQueryData.monitors[0]['bs_id'];
		lineMonitors.show(data.defaultQueryData.monitors);
		if(data.defaultQueryData.echartData){
			detailDiv.show();
			queryMonitorResultNoDataDiv.hide();
			iceMonitorChart.show(data.defaultQueryData.echartData);
			iceMonitorTable.show(data.defaultQueryData.tableData);
		}else{
			queryMonitorResultNoDataDiv.show();
			detailDiv.hide();
		}
	});
}
//query 一共三个地方使用，换线的时候，换设备的时候，换时间的时候。
function query(isMonitorQuery){
	startDate = $('#start').val();
	endDate = $('#end').val();
	var url = "/rest/ice/getLineMonitorListDialogQueryData/"+currentLineName+"/"+startDate+"/"+endDate;
	if(isMonitorQuery){
		url += "/"+currentMonitorId;
		queryMonitorResultDiv.hide();
		queryMonitorResultLoadingDiv.show();
	}else{
		url += "/undefined";
		queryLineResultDiv.hide();
		queryLineResultLoadingDiv.show();
	}
	
	var queryIndexCopy = Math.random();
	queryIndex = queryIndexCopy;
	$.getJSON(url, function(result) {
		if(queryIndex == queryIndexCopy){
			if(isMonitorQuery){
				queryMonitorResultLoadingDiv.hide();
				queryMonitorResultDiv.show();
			}else{
				currentMonitorId = result.monitors[0]['bs_id'];
				queryLineResultLoadingDiv.hide();
				queryLineResultDiv.show();
			}
			if(result.monitors.length > 0){
				lineMonitors.show(result.monitors);
				if(result.echartData){
					detailDiv.show();
					queryMonitorResultNoDataDiv.hide();
					iceMonitorChart.show(result.echartData);
					iceMonitorTable.show(result.tableData);
				}
			}else{
				//查不到数据
				queryMonitorResultNoDataDiv.show();
				detailDiv.hide();
			}
			
		}
	});
}
function drawLineNames(ices) {
	var lineNameList = $('#lineNameUl');
	lineNameList.html("");
	if (ices.length > 0) {
		for ( var i in ices) {
			var lineName = ices[i];
			var c = i == "0"?"selected":"";
			lineNameList
					.append('<li class="nav nav-pills"><a class="'+c+'" href="javascript:void(0);" onclick="onLineSelected(\''
							+ lineName + '\',this)">' + lineName + '</a></li>');
		}
	}
}

function LineMonitors(){
	var lineMonitorList = $('#lineMonitorUl');
	var lineMonitorInfoDiv = $('#monitorInfo');
	function show(monitors){
		lineMonitorList.html("");
		if (monitors.length > 0) {
			for ( var i in monitors) {
				var name = monitors[i]['bs_id'];
				var pole = monitors[i]['pole_name'];
				var c = name == currentMonitorId?"selected":"";
				lineMonitorList
				.append('<li class="nav nav-pills"><a class="'+c+'" href="javascript:void(0);" onclick="onMonitorSelected(\''
						+ name + '\',this)">' + name +'<span style="float:right">#'+pole+'杆塔</span></a></li>');
			}
		}
	}
	return {
		show:show,//参数monitors
	};
}

function onLineSelected(lineName,ele){
	if(ele){
		$('#lineNameUl .selected').removeClass('selected');
		$(ele).addClass('selected');
		currentLineName = lineName;
		currentMonitorId = null;
		query(false);
	}
}
function onMonitorSelected(monitorId,ele){
	if(ele){
		$('#lineMonitorUl .selected').removeClass('selected');
		$(ele).addClass('selected');
		currentMonitorId = monitorId;
		query(true);
	}
}

function IceMonitorChart(){
	
	var iceChart;
	var iceChartDiv = $('#iceChart');
	function show(data){
		drawCharts(data);
	}
	
	function drawCharts(data){
		var legends = {};
		if(iceChart){
			iceChart.getChart().clear();
		}
		iceChart = new CategoryLine('iceChart');
		iceChart.setxAxisTitle("时间").setSubTitle(startDate+' ~ '+endDate);
		var colors = [];
		for(var i in data){
			iceChart.setyAxis(data[i].data).setyAxisName(data[i].phase).setyAxisTitle("毫米");
			legends[data[i].phase]=true;
			colors.push(data[i].color);
		}
		iceChart.setDataZoom(true).setDataView(false).setMagicType(false);
		
		var option = iceChart.getOption();
		option.xAxis.min = startDate+" 00:00:00";
		option.xAxis.max = endDate+" 23:59:59";
		option.color = colors;
		option.xAxis.type = 'time';
		option.title.subtextStyle = {color:'black'};
		option.tooltip = {
				trigger:'axis',
				formatter:function(params, ticket, callback){
					var str = '';
					var d = new Date(params[0].value[0]);
					var m = getDouble(d.getMonth()+1);
					var day = getDouble(d.getDate());
					var h = getDouble(d.getHours());
					var min = getDouble(d.getMinutes());
					str += '<span>'+m+'-'+day+' '+h+':'+min+'</span><br/>';
					for(var i in data){
						if(legends[data[i].phase]){
							var value = '-';
							for(var j in params){
								if(data[i].phase == params[j].seriesName){
									value = params[j].value[1];
									break;
								}
							}
							str += '<span><span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:'+data[i].color
							+';"></span>'+data[i].phase+'：'+value+'</span><br/>';
						}
					}
					str += '';
					return str;
				}
		};
		option.dataZoom = [{ type:'inside'},
		                   {
			type:'slider',
			dataBackground :{
				lineStyle:{
					color:'blue',
					opacity:1
				}
			}
		                   }];
		
		for(var i in option.series){
			var series = option.series[i];
			var num = 0;
			for(var j in series.data){
				if(series.data[j][1] != "-"){
					num ++;
					if(num > 1){
						break;
					}
				}
			}
			series.showSymbol = num>1?false:true;
			series.label.normal.show = num>1?false:true;
			series.label.emphasis.show = true;
			series.label.emphasis.position = 'top';
			series.areaStyle = {'normal':{'color':'rgba(188,247,241,0.3)'}};
			series.smooth = true;
			series.connectNulls = false;
		}
		iceChart.show();
		iceChart.getChart().on('legendselectchanged',function(params){
			legends = params.selected;
		});
	}
	function resizeChart(){
		if(iceChart){
			iceChart.getChart().resize();
		}
	};
	return {
		show:show, //参数bsId,start,end
		resizeChart:resizeChart
	};
}
function IceMonitorTable(){
	var table;
	function show(data){
		drawTable(data);
	}
	function drawTable(data){
		if(table){
			table.getTable().destroy();
		}
		var dataset = [];
		for(var i=0;i<data.length;i++){
			var d = data[i];
			dataset[i] = [i+1,getTime(new Date(d['rec_update_time'])),d['rec_phase'],d['rec_ice_height']];
		}
		var columns = ['序号','时间','相位','厚度'];
		var opt = MyTable.getDefaultOptions();
		opt.paging = true;
		opt.pageLength = 10;
		table = new MyTable("iceMonitorTable", columns, opt);
		table.setDataSet(dataset);
		table.show();
	}
	return {
		show:show,//参数 data
	};
}
function getDouble(n){
	return n>9?n:"0"+n;
}
function getTime(t){
	if(t instanceof Date){
		var y = t.getFullYear();
		var M = t.getMonth()+1;
		var d = t.getDate();
		var h = t.getHours();
		var m = t.getMinutes();
		var s = t.getSeconds();
		return getDouble(y)+"-"+getDouble(M)+"-"+getDouble(d)+" "
		+getDouble(h)+":"+getDouble(m)+":"+getDouble(s);
	}else{
		return d?d:'';
	}
}
function getDate(t){
	if(t instanceof Date){
		var y = t.getFullYear();
		var M = t.getMonth()+1;
		var d = t.getDate();
		return getDouble(y)+"-"+getDouble(M)+"-"+getDouble(d);
	}else{
		return d?d:'';
	}
}
